package com.sxfans.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 处理字符串数组等相关方法。
 * 
 * @author suxin
 */
public class StringUtils {
//    /** 行分隔符 */
//    public static final String LINE_SEPERATOR = (String) java.security.AccessController.doPrivileged(
//            new sun.security.action.GetPropertyAction("line.separator"));
    /** the logger */
    // private static Logger logger = Logger.getLogger(FileUtils.class);
    /**
     * 将数据串接成一个长字符串，中间使用指定的分隔符进行分隔
     * 
     * @param array
     *            数组
     * @param sep
     *            指定的分隔符
     * @return 串接后的字符串
     */
    public static String arrayJoin(String[] array, String sep) {
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < array.length; i++) {
            result.append(array[i]).append(sep);
        }
        int len = result.length();
        if (len > 0) {
            result.setLength(len - sep.length());
        }
        return result.toString();
    }
    
    public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }
    
    /**
     * 将字符串str中的str1替换为str2
     * 
     * @param str
     *            str
     * @param str1
     *            str1
     * @param str2
     *            str2
     * @return 替换后的结果
     */
    public static String replace(String text, String searchString, String replacement) {
    	int max = -1;
        if (isBlank(text) || isBlank(searchString) || replacement == null) {
            return text;
        }
        int start = 0;
        int end = text.indexOf(searchString, start);
        if (end == -1) {
            return text;
        }
        int replLength = searchString.length();
        int increase = replacement.length() - replLength;
        increase = (increase < 0 ? 0 : increase);
        increase *= (max < 0 ? 16 : (max > 64 ? 64 : max));
        StringBuffer buf = new StringBuffer(text.length() + increase);
        while (end != -1) {
            buf.append(text.substring(start, end)).append(replacement);
            start = end + replLength;
            if (--max == 0) {
                break;
            }
            end = text.indexOf(searchString, start);
        }
        buf.append(text.substring(start));
        return buf.toString();
    }
    
    /**
     * 将一个输入字符串按照分隔符号拆解为对应的字符串数组，和JAVA中的split区别是分隔符可以是任意字符串而不用担心正则表达式问题
     * @param src       输入字符串
     * @param delm      分隔符
     * @return          拆解后的字符串数组
     */
    public static String[] split(String src, String delm) {
        //return org.apache.commons.lang.StringUtils.split(src, delm);
    	return null;
    }

    /**
     * 转义符编码
     * 
     * @param str
     *            str
     * @return 编码后的字符串
     */
    public static String esc(String str) {
        str = StringUtils.replace(str, "\\", "\\\\");
        str = StringUtils.replace(str, "\r\n", "\\r\\n");
        str = StringUtils.replace(str, "\r", "\\r");
        str = StringUtils.replace(str, "\n", "\\n");
        str = StringUtils.replace(str, "\t", "\\t");
        return str;
    }

    /**
     * 转义符解码
     * 
     * @param str
     *            str
     * @return 解码后的字符串
     */
    public static String unesc(String str) {
        str = StringUtils.replace(str, "\\\\", "\\");
        str = StringUtils.replace(str, "\\r\\n", "\r\n");
        str = StringUtils.replace(str, "\\r", "\r");
        str = StringUtils.replace(str, "\\n", "\n");
        str = StringUtils.replace(str, "\\t", "\t");
        return str;
    }

    /**
     * 根据前缀和后缀查找字串 例如：源字串为 String source = this is <@USER_NAME@> speeking:<@CONTENT@>
     * 现在要把<@USER_NAME@>，<@CONTENT@>提取出来可以使用search(source,"<@","@>");
     * 则返回数组内容为：USER_NAME,CONTENT
     * 
     * @param source
     *            源字符串
     * @param prefix
     *            前缀
     * @param suffix
     *            后缀
     * @return 查找结果的String数组
     */
    public static String[] search(String source, String prefix, String suffix) {
        String regexp = "\\" + prefix + "(\\w+).*?\\" + suffix;
        Pattern p = Pattern.compile(regexp);
        Matcher matcher = p.matcher(source);

        List list = new ArrayList();
        while (matcher.find()) {
            list.add(matcher.group(1));
        }
        String[] result = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            result[i] = (String) list.get(i);
        }
        return result;
    }
    
    /**
     * 根据指定的正则表达式返回匹配的数组
     * @author chuaq
     * @param source                     参数：源字符串
     * @param regexp                     参数：正则表达式
     * @return String[]                  返回值
     */
    public static String[] search(String source, String regexp) {
        Pattern p = Pattern.compile(regexp);
        Matcher matcher = p.matcher(source);

        List list = new ArrayList();
        while (matcher.find()) {
            list.add(matcher.group(1));
        }
        String[] result = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            result[i] = (String) list.get(i);
        }
        return result;
    }
    
    /**
     * 人民币小写金额转换为大写金额
     * 
     * @param input 要转换为大写的金额数
     * @return 转换后的大写字母
     * @author wangxia
     * @date 2006/4/3 add
     */
    public static String numToChinese(String input) {

        char[] cap = {'零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'};
        char[] units = {'分', '角', '整', '元', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟'};

        String temp = input.trim();
        String result = "";
        int len = 0;
        //统计小数点前的位数
        if (temp.indexOf(".") == -1) {
            len = temp.length();
        } else {
            len = temp.indexOf(".");
        }
        if (len > units.length - 3) {
            return ("输入数字为: " + input + " 最大只能精确到仟亿，小数点只能两位！");
        }
        int n1 = 0;
        char num;
        char unit;

        for (int i = 0; i < temp.length(); i++) {
            if (i > len + 2) {
                break;
            }
            if (i == len) {
                continue;
            }
            n1 = Integer.parseInt(String.valueOf(temp.charAt(i)));
            num = cap[n1];
            n1 = len - i + 2;
            unit = units[n1];
            result = result + num + unit;
        }
        if ((len == temp.length()) || (len == temp.length() - 1)) {
            result = result.concat("整");
        }
        if (len == temp.length() - 2) {
            result = result.concat("零分");
        }
        return result;
    }

    /**
     * JavaScript escape/unescape 编码的 Java 实现
     */
     private static final String[] ESCAPE_HEX = {
         "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F",
         "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F",
         "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F",
         "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F",
         "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F",
         "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F",
         "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F",
         "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F",
         "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F",
         "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F",
         "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF",
         "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF",
         "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF",
         "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF",
         "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF",
         "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF"
     };

     /**
      * JavaScript escape/unescape 编码的 Java 实现
      */
     private static final byte[] ESCAPE_VAL = {
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0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, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
         0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F
     };

     /**
      * JavaScript escape/unescape 编码的 Java 实现,这里实现的是escape方法,完全可以和javascript的方法兼容.
      * @param s     输入需要编码的字符串
      * @return      按照javascript方式编码后的结果
      */
     public static String escape(String s) {
         StringBuffer sbuf = new StringBuffer();
         int len = s.length();
         for (int i = 0; i < len; i++) {
             int ch = s.charAt(i);
             if (ch == ' ') { // space : map to '+'
                 sbuf.append('+');
             } else if ('A' <= ch && ch <= 'Z') { // 'A'..'Z' : as it was
                 sbuf.append((char) ch);
             } else if ('a' <= ch && ch <= 'z') { // 'a'..'z' : as it was
                 sbuf.append((char) ch);
             } else if ('0' <= ch && ch <= '9') { // '0'..'9' : as it was
                 sbuf.append((char) ch);
             } else if (ch == '-' || ch == '_' // unreserved : as it was
                 || ch == '.' || ch == '!'
                 || ch == '~' || ch == '*'
                 || ch == '\'' || ch == '('
                 || ch == ')') {
                 sbuf.append((char) ch);
             } else if (ch <= 0x007F) { // other ASCII : map to %XX
                 sbuf.append('%');
                 sbuf.append(ESCAPE_HEX[ch]);
             } else { // unicode : map to %uXXXX
                 sbuf.append('%');
                 sbuf.append('u');
                 sbuf.append(ESCAPE_HEX[(ch >>> 8)]);
                 sbuf.append(ESCAPE_HEX[(0x00FF & ch)]);
             }
         } //end for
         return sbuf.toString();
     }
     
     /**
      * JavaScript escape/unescape 编码的 Java 实现,这里实现的是unescape方法,完全可以和javascript的方法兼容.
      * @param s     输入需要解码的字符串
      * @return      按照javascript方式解码后的结果
      */
     public static String unescape(String s) {
         StringBuffer sbuf = new StringBuffer();
         int i = 0;
         int len = s.length();
         while (i < len) {
             int ch = s.charAt(i);
             if (ch == '+') { // + : map to ' '
         sbuf.append(' ');
     } else if ('A' <= ch && ch <= 'Z') { // 'A'..'Z' : as it was
         sbuf.append((char) ch);
     } else if ('a' <= ch && ch <= 'z') { // 'a'..'z' : as it was
         sbuf.append((char) ch);
     } else if ('0' <= ch && ch <= '9') { // '0'..'9' : as it was
         sbuf.append((char) ch);
     } else if (ch == '-' || ch == '_' // unreserved : as it was
         || ch == '.' || ch == '!'
         || ch == '~' || ch == '*'
         || ch == '\'' || ch == '('
         || ch == ')') {
         sbuf.append((char) ch);
     } else if (ch == '%') {
         int cint = 0;
         if ('u' != s.charAt(i + 1)) { // %XX : map to ascii(XX)
             cint = (cint << 4) | ESCAPE_VAL[s.charAt(i + 1)];
             cint = (cint << 4) | ESCAPE_VAL[s.charAt(i + 2)];
             i += 2;
         } else { // %uXXXX : map to unicode(XXXX)
                     cint = (cint << 4) | ESCAPE_VAL[s.charAt(i + 2)];
                     cint = (cint << 4) | ESCAPE_VAL[s.charAt(i + 3)];
                     cint = (cint << 4) | ESCAPE_VAL[s.charAt(i + 4)];
                     cint = (cint << 4) | ESCAPE_VAL[s.charAt(i + 5)];
                     i += 5;
                 }
                 sbuf.append((char) cint);
             }
             i++;
         }
         return sbuf.toString();
     }

     /**
      * 从一个字符串连接串中删除某个值。如：从a,b,b,c中删除c，得到a,b,b；删除b，得到a,c。
      * @param line     字符串
      * @param sep      连接符号
      * @param value    要删除的值
      * @return         结果
      */
     public static String removeValueFromLine(String line, String sep, String value) {
         if (line.equals(value)) {
             return "";
         }
         StringBuffer lineBuffer = new StringBuffer(sep).append(line).append(sep);
         StringBuffer valueBuffer = new StringBuffer(sep).append(value).append(sep);
         String result = lineBuffer.toString().replaceAll(valueBuffer.toString(), sep);
         return result.substring(1, result.length() - 1);
     }
     /**
      * 判断字符串是否为时间日期
      * @param str 字符串
      * @return 结果 true(是)/false(不是) 
      */
     public static boolean isDateTime(String str) {
        boolean result = false;
        String regExp = "(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2})++";
        if (str.matches(regExp)) {
            result = true;
        }
        return result;
     }
     /**
      * 判断字符串是否为日期,格式(2008-05-27)
      * @param str 字符串
      * @return 结果 true(是)/false(不是)
      */
     public static boolean isDate(String str) {
         boolean result = false;
         String regExp = "(\\d{4}-\\d{2}-\\d{2})++";
         if (str.matches(regExp)) {
             result = true;
         }
         return result;
     }
     /**
      * 判断字符串是否为年月,格式(2008-05)
      * @param str 字符串
      * @return 结果 true(是)/false(不是)
      */
     public static boolean isYearMonth(String str) {
         boolean result = false;
         String regExp = "(\\d{4}-\\d{2})++";
         if (str.matches(regExp)) {
             result = true;
         }
         return result;
     }
     /**
      * 判断字符串是否包含中文字符
      * @param str 字符串
      * @return 结果 true 包含中文字符/ false 不包含
      */
     public static boolean includeChineseChar(String str) {
         String regExp = "[\u4e00-\u9fa5]++";
         Matcher matcher = Pattern.compile(regExp).matcher(str);
         while (matcher.find()) {
             return (true);
         }
         return false;
     }
     /**
      * 匹配正则表达式
      * @param str 字符串 
      * @param regExp 正则表达式
      * @return result 匹配结果 true匹配成功，false 匹配失败
      */
    public static boolean matcherExp(String str, String regExp) {
        boolean result = false;
        java.util.regex.Matcher matcher = java.util.regex.Pattern.compile(regExp).matcher(str);
        result = matcher.matches();
        return result;
    }
    
	public static String replaceByLen(String data,String repStr,int start,int end)
	{
		String str1 = data.substring(0,start);
		String str2 = data.substring(end-1,data.length());
		return str1+repStr+str2;
	}
}
